export function tplReplace(template,templateObject){
    
    return template().replace(/\{\{(.*?)\}\}/g,(node,key) => {
        return templateObject[key.trim()];
    })
};


export function scrollTop(){
    setTimeout(() => {
        window.scrollTo(0,0); 
    })
}

export function setPageData(data,count){
    const len = data.length;
    let pageData = [];
    let index = 0;

    while(index < len){
        pageData.push(data.slice(index, index += count));
    };

    return pageData; 

}
export function scrollToBottom(callback){
    if(_getScrollTop() + _getWindowHeight() + 1 > _getScrollHeight()){
       callback();
    }
}

export function getParentNode(target){
    if(target.className.split(' ')[0] === 'news-item'){
        return target;
    };
    while(target= target.parentNode){
        if(target.className.split(' ')[0] === 'news-item'){
            return target;
        }
    }
}

export function getUrlQueryValue(key){
    const reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)','i');
    const res = window.location.search.substring(1).match(reg);
    console.log(res);

    return res !== null ? decodeURIComponent(res[2]) : null
}

/****************************** 内部方法 *********************************/

/* 获取滚动条的距离  */
function _getScrollTop() {
    var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
    if (document.body) {
        bodyScrollTop = document.body.scrollTop;
    }
    if (document.documentElement) {
        documentScrollTop = document.documentElement.scrollTop;
    }
    scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
    return scrollTop;
  }
   
  /* 获取整个 文档的高度, (包括滚动条的距离) */
  function _getScrollHeight() {
    var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
    if (document.body) {
        bodyScrollHeight = document.body.scrollHeight;
    }
    if (document.documentElement) {
        documentScrollHeight = document.documentElement.scrollHeight;
    }
    scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
    return scrollHeight;
  }
  
  /*  获取窗口的高度 不包含 border 和 margin */
  function _getWindowHeight() {
    var windowHeight = 0;
    if (document.compatMode == "CSS1Compat") {
        windowHeight = document.documentElement.clientHeight;
    } else {
        windowHeight = document.body.clientHeight;
    }
    return windowHeight;
  }